#!/usr/bin/python

import commonLib
import sys
import pickle
import os
from time import sleep
#The goal of this script is to assess the initcalls
#and put the results in a NodeCollection

#First change the status file

f = open("./../status"+sys.argv[1],'w')
f.write("Currently assessing the initcalls. (<1 min)")
f.close()

#Get the number of initcalls
f = open('NodeCollection','r')
lines = f.readlines()
f.close()

content=""
for line in lines:
	content+= line

NodeCollection = pickle.loads(content)

#Generate a basic deltaTable
deltaTable = []
for i in range(0,len(NodeCollection)):
	deltaTable.append(commonLib.Node(i))
	deltaTable[i].delta = 1
	deltaTable[i].parents.append(-1)
deltaTable.reverse()

commonLib.generateKernelCode('PARALLEL','NO',deltaTable,2, 'YES')	
commonLib.compileKernel()
mySerialPortInterface = commonLib.serialPortInterface(int(sys.argv[1]))

command = "net init;load -b tftp://"+commonLib.getHostIP()+"/vmlinux.bin "+commonLib.getOptions()['loadingAddress']+";go\n" 
print command
mySerialPortInterface.writeCommand(command)	

boardIP =mySerialPortInterface.analyzeInputStream('getBoardIP')
reference =mySerialPortInterface.analyzeInputStream('getDelta')

for i in range(0,len(NodeCollection)):
	NodeCollection[i].delta = int((float(mySerialPortInterface.analyzeInputStream('getDelta')-reference)/reference)*1000000000)
	if NodeCollection[i].delta < 0:
		NodeCollection[i].delta = 0
sleep(10)
#Reboot the board "by hand"
import socket
from time import sleep

HOST=boardIP
PORT = 23

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
sleep(2)

s.send("root\n")
sleep(2)
s.send("reboot\n")
sleep(2)
s.close()


#Then write what we have in a file
f = open('NodeCollectionWithDeltas','w')
f.write(pickle.dumps(NodeCollection))
f.close()

